package pers.karl.security.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author karl
 * @description:
 * @create 2020-08-14 00:30
 */
public class ResponseUtils {

    public static Map<String,Object> getResultInfo(int code, String errorMsg) {
        Map<String,Object> resultInfo = new HashMap<>(2);
        resultInfo.put("code", code);
        resultInfo.put("msg", errorMsg);
        return resultInfo;
    }

    public static Map<String,Object> getSuccessResultInfo(int code, Object data) {
        Map<String,Object> resultInfo = new HashMap<>(2);
        resultInfo.put("code", code);
        resultInfo.put("data", data);
        return resultInfo;
    }

    /**
     * 写入json数据作为响应数据
     * @param response
     * @param httpStatus
     * @param errorMsg
     * @throws IOException
     */
    public static void writeJson(HttpServletResponse response, HttpStatus httpStatus, String errorMsg) throws IOException {
        response.setStatus(httpStatus.value());
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(new ObjectMapper().writeValueAsString(getResultInfo(httpStatus.value(), errorMsg)));
    }

    public static void writeJsonSuccessData(HttpServletResponse response, Object data) throws IOException {
        response.setStatus(HttpStatus.OK.value());
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(new ObjectMapper().writeValueAsString(getSuccessResultInfo(HttpStatus.OK.value(), data)));
    }

}
